const App = getApp();

Page({
  data: {
    // 搜索框样式
    searchColor: "rgba(0,0,0,0.4)",
    searchSize: "15",
    searchName: "搜索商品",
    classifyData: [], //分类数据
    showBottomPopup: false,
    specData: {}, //多规格
    goods_price: 0, // 商品价格
    line_price: 0, // 划线价格
    stock_num: 0, // 库存数量
    goods_num: 1, // 商品数量
    goods_name: '', //商品名称
    goods_sku_id: 0, // 规格id
    goodsId: '', //商品ID
    cart_total_num: 0, // 购物车商品总数量
    page: 1, //当前页
    lastPage: 0, //最后一页
    showSpec: false,

    // 列表高度
    scrollHeight: 0,

    // 一级分类：指针
    curNav: true,
    curIndex: 0,

    // 分类列表
    list: [],

    // show
    notcont: false
  },
  // 记录规格的数组
  goods_spec_arr: [],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let _this = this;
    // 设置分类列表高度
    _this.setListHeight();
    // 获取分类列表
    _this.getCategoryList();
  },

  /**
   * 设置分类列表高度
   */
  setListHeight() {
    let _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          scrollHeight: res.windowHeight - 47,
        });
      }
    });
  },

  /**
   * 获取分类列表
   */
  getCategoryList() {
    let _this = this;
    App._get('category/index', {}, result => {
      let data = result.data;
      _this.setData({
        list: data.list,
        templet: data.templet,
        curNav: data.list.length > 0 ? data.list[0].category_id : true,
        notcont: !data.list.length
      });

      let lists = this.data.list

      lists.unshift({
        "category_id": "",
        "name": "全部",
      })

      this.setData({
        list: lists,
        curNav: ""
      })

      this.getGoods(_this.data.curNav)
    });
  },

  /**
   * 一级分类：选中分类
   */
  selectNav(e) {
    let _this = this;
    _this.setData({
      curNav: e.target.dataset.id,
      curIndex: parseInt(e.target.dataset.index),
      scrollTop: 0,
      classifyData: []
    });
    this.getGoods(e.target.dataset.id)
  },
  // 获取二级分类
  getGoods(id) {
    let _this = this;
    let page = this.data.page;

    App._get('goods/lists', {
      category_id: id,
      search: '',
      sortType: '',
      sortPrice: '',
      page
    }, result => {
      if (result.code == 1) {
        let list = result.data.list;
        _this.setData({
          page: list.current_page,
          lastPage: list.last_page,
          classifyData: _this.data.classifyData.concat(list.data)
        })
      }
    });
  },
  /**
   * 设置分享内容
   */
  onShareAppMessage() {
    let _this = this;
    return {
      title: _this.data.templet.share_title,
      path: '/pages/category/index?' + App.getShareUrlParams()
    };
  },
  /**
   * 初始化商品多规格
   */
  initManySpecData: function(data) {
    for (let i in data.spec_attr) {
      for (let j in data.spec_attr[i].spec_items) {
        if (j < 1) {
          data.spec_attr[i].spec_items[0].checked = true;
          this.goods_spec_arr[i] = data.spec_attr[i].spec_items[0].item_id;
        }
      }
    }
    return data;
  },
  selectType(e) {
    let id = e.currentTarget.id;
    let goods_name = e.currentTarget.dataset.name;

    let _this = this;
    let data = {}

    this.setData({
      goodsId: id,
      specData: {},
      goods_name
    })

    App._get('goods/detail', {
      goods_id: id
    }, function(result) {
      data.goods_sku_id = result.data.detail.sku[0].spec_sku_id;
      data.goods_price = result.data.detail.sku[0].goods_price;
      data.line_price = result.data.detail.sku[0].line_price;
      data.stock_num = result.data.detail.sku[0].stock_num;

      if (result.data.detail.spec_type == 20) {
        data.specData = _this.initManySpecData(result.data.specData);
        _this.setData(
          data
        )
        _this.setData({
          showSpec: true
        })
      }
    });
  },
  /**
   * 点击切换不同规格
   */
  modelTap: function(e) {
    let attrIdx = e.currentTarget.dataset.attrIdx,
      itemIdx = e.currentTarget.dataset.itemIdx,
      specData = this.data.specData;

    for (let i in specData.spec_attr) {
      for (let j in specData.spec_attr[i].spec_items) {
        if (attrIdx == i) {
          specData.spec_attr[i].spec_items[j].checked = false;
          if (itemIdx == j) {
            specData.spec_attr[i].spec_items[itemIdx].checked = true;
            this.goods_spec_arr[i] = specData.spec_attr[i].spec_items[itemIdx].item_id;
          }
        }
      }
    }
    this.setData({
      specData
    });
    // 更新商品规格信息
    this.updateSpecGoods();
  },
  /**
   * 更新商品规格信息
   */
  updateSpecGoods: function() {
    let spec_sku_id = this.goods_spec_arr.join('_');

    // 查找skuItem
    let spec_list = this.data.specData.spec_list,
      skuItem = spec_list.find((val) => {
        return val.spec_sku_id == spec_sku_id;
      });

    // 记录goods_sku_id
    // 更新商品价格、划线价、库存
    if (typeof skuItem === 'object') {
      this.setData({
        goods_sku_id: skuItem.spec_sku_id,
        goods_price: skuItem.form.goods_price,
        line_price: skuItem.form.line_price,
        stock_num: skuItem.form.stock_num,
      });
    }
  },
  //加入购物车
  addShop(e) {
    let _this = this;
    let goodsId;
    let id = e.currentTarget.id;
    if (id) {
      goodsId = id
      _this.setData({
        goods_sku_id: 0
      })
    } else {
      goodsId = this.data.goodsId
    }

    App._post_form('cart/add', {
      goods_id: goodsId,
      goods_num: _this.data.goods_num,
      goods_sku_id: _this.data.goods_sku_id,
    }, function(result) {
      App.showSuccess(result.msg);
      _this.setData(result.data);
    });
  },
  // 下拉加载下一页数据
  scrollBottom() {
    let id = this.data.curNav;
    let page = this.data.page;
    let lastPage = this.data.lastPage;

    if (page < lastPage) {
      page++;
      this.setData({
        page
      })
      this.getGoods(id)
    } else {
      wx.showToast({
        title: '亲，没有更多了',
        icon: 'none'
      })
    }
  },
  redirectDetail(e) {
    let id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/goods/index?goods_id=' + id
    })
  },
  //关闭选择规格窗口
  closeSpec() {
    this.setData({
      showSpec: false
    })
    this.goods_spec_arr = []
  },
  redirectShop() {
    wx.switchTab({
      url: '/pages/flow/index',
    })
  }
});